package com.liuww.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {

	private Socket socket;
	public final static String WEB_ROOT = ClassLoader.getSystemResource("").getPath();
	
	public Processor(Socket socket){
		this.socket = socket;
	}
	
	@Override
	public void run(){
		try {
			InputStream in = socket.getInputStream();
			PrintStream out = new PrintStream(socket.getOutputStream());
			parse(in, out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String parse(InputStream in, PrintStream out) {
		BufferedReader buff = new BufferedReader(new InputStreamReader(in));
		try {
			String httpMessage = buff.readLine();
			String[] httpContent = httpMessage.split(" ");
			int length = httpContent.length;
			if (length != 3) {
				sendErrorMessage(400, "Client query error!", out);
			}
			System.out.println("code: " + httpContent[0] +", fileName: "+ httpContent[1] +", version: "+ httpContent[2]);
			String fileName = httpContent[1];
			sendFile(fileName, out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void sendErrorMessage(int errorCode, String errorMessage, PrintStream out){
		out.println("HTTP/1.0 " + errorCode +" "+ errorMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<title>error</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode: " + errorCode +" ErrorMessage: "+ errorMessage + "</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	
	public void sendFile(String fileName, PrintStream out){
		File file = new File(WEB_ROOT + fileName);
		if (!file.exists()){
			sendErrorMessage(404, "File Not Found!", out);
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte[] content = new byte[(int)file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
